/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.trello.rxlifecycle4.harmony;

import ohos.agp.components.Component;

import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;

import static io.reactivex.rxjava3.openharmony.MainThreadDisposable.verifyMainThread;

/**
 * This is an observable class
 */
final class ViewDetachesOnSubscribe implements ObservableOnSubscribe<Object> {
    static final Object SIGNAL = new Object();
    final Component view;

    ViewDetachesOnSubscribe(Component view) {
        this.view = view;
    }

    @Override
    public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
        verifyMainThread();
        EmitterListener listener = new EmitterListener(emitter);
        emitter.setDisposable(listener);
        view.setBindStateChangedListener(listener);
    }

    /**
     * This is listener class for bind state change of component
     */
    class EmitterListener extends MainThreadDisposable implements Component.BindStateChangedListener {
        final ObservableEmitter<Object> emitter;

        EmitterListener(ObservableEmitter<Object> emitter) {
            this.emitter = emitter;
        }

        @Override
        public void onComponentBoundToWindow(Component component) {
            // Do nothing
        }

        @Override
        public void onComponentUnboundFromWindow(Component component) {
            emitter.onNext(SIGNAL);
        }

        @Override
        protected void onDispose() {
            view.removeBindStateChangedListener(this);
        }
    }
}
